#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Feature配置加载工具
处理feature配置文件的加载和解析
"""

import os
import logging

def generate(env):
    """
    生成feature配置加载工具
    
    Args:
        env: SCons环境
    """
    _load_feature_config(env)

def exists(env):
    """
    检查工具是否存在
    
    Args:
        env: SCons环境
        
    Returns:
        True
    """
    return True

def _load_feature_config(env):
    """
    加载feature配置文件
    
    Args:
        env: SCons环境
    """
    # 检查是否设置了PROJECT_FEATURE_CONFIG环境变量
    feature_config_file = os.environ.get('PROJECT_FEATURE_CONFIG')
    if not feature_config_file:
        return
    
    if not os.path.exists(feature_config_file):
        logging.warning(f"Feature config file not found: {feature_config_file}")
        return
    
    logging.info(f"Loading feature config from: {feature_config_file}")
    
    try:
        with open(feature_config_file, 'r', encoding='utf-8') as f:
            for line_num, line in enumerate(f, 1):
                line = line.strip()
                
                # 跳过空行和注释行
                if not line or line.startswith('#'):
                    continue
                
                # 解析feature配置行
                if '=' in line:
                    key, value = line.split('=', 1)
                    key = key.strip()
                    value = value.strip()
                    
                    # 移除引号
                    if value.startswith('"') and value.endswith('"'):
                        value = value[1:-1]
                    elif value.startswith("'") and value.endswith("'"):
                        value = value[1:-1]
                    
                    # 设置到SCons环境中
                    env[key] = value
                    
                    # 同时添加到全局宏定义中，确保所有编译目标都能获得这些宏定义
                    if value == '1' or value == 'true' or value == 'True':
                        # 对于值为1或true的宏，只定义宏名
                        env.Append(CPPDEFINES=[key])
                    else:
                        # 对于有具体值的宏，定义为(key, value)格式
                        env.Append(CPPDEFINES=[(key, value)])
                    
                    logging.info(f"  Feature: {key} = {value} (added to CPPDEFINES)")
                else:
                    logging.warning(f"Invalid feature config line {line_num}: {line}")
    
        # 添加成功加载的日志信息
        logging.info("Feature config loaded successfully")
        
    except Exception as e:
        logging.error(f"Failed to load feature config: {e}")
        raise